import { login, getUserInfo, getProfile } from '@/api/user.js'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth.js'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    // 移除token
    removeToken (state) {
      state.token = null
      removeToken()
    },
    // 保存用户数据
    setUserInfo (state, newData) {
      state.userInfo = newData
    },
    // 移除用户数据
    removeUserInfo (state) {
      state.userInfo = {}
    }

  },
  actions: {
    // 登录请求
    async login (context, data) {
      const res = await login(data)
      // console.log(res)
      setTimeStamp() // 保存token获取的时间戳
      context.commit('setToken', res)
    },
    // 获取用户信息
    async getUserInfo (context) {
      const res = await getUserInfo()
      // console.log(res)
      const profile = await getProfile(res.userId)
      // console.log(profile)
      const data = { ...res, ...profile }
      context.commit('setUserInfo', data)
    },
    logout ({ commit }) { // context 代表store对象
      commit('removeToken')
      commit('removeUserInfo')
    }
  }
}
